<?php
class ApiController extends FrontController
{
	public function indexAction()
	{
	}
	
	public function loadAction()
	{
		$paths = CF_App::getInstance()->getControler()->getPath();
		CF_Loader::addIncludePath($paths);
		$controllers = array();
		
		# regx pattern for match controller
		$cPattern = CF_App::getInstance()->getControler()->getControllerClassFormat();
		$cPattern = str_replace('%s', '(\w+)', $cPattern);
		$cPattern = '/' . $cPattern . '/';
		
		# regx pattern for match action
		$aPattern = CF_App::getInstance()->getControler()->getActionMethodFormat();
		$aPattern = str_replace('%s', '(\w+)', $aPattern);
		$aPattern = '/' . $aPattern . '/';
		
		# get all controller class name
		foreach ($paths as $path){
			$dir = dir($path);
			while(false !== ($f = $dir->read())){
				if('.' == $f || '..' == $f || '.php' !== substr($f, -4)) continue;
				
				$class = str_replace('.php', '', $f);
				if(!preg_match($cPattern, $class, $matches)) continue;
				$controllers[strtolower($matches[1])] = $this->_getAction($class, $aPattern);
			}
			$dir->close();
		}
		
		$result = array(
			'url' => 'index.php',
			'namespace' => 'API',
			'type' => 'remoting',
			'enableBuffer' => false,
			'actions' => $controllers
		);
		$this->getResponse()->setBody('Ext.ns("Ext.App"); Ext.App.REMOTING_API = ' . json_encode($result));
	}
	
	protected function _getAction($className, $aPattern)
	{
		$rClass = new ReflectionClass($className);
		$actions = array();
		foreach($rClass->getMethods() as $rMethod){
			$name = $rMethod->name;
			if(!preg_match($aPattern, $name, $matches)) continue;
			if(!$rMethod->isPublic()) continue;
			
			$action = array('name' => $matches[1]);
			$action['formHandler'] = (boolean) preg_match('/@formHandler/', $rMethod->getDocComment());
			$action['len'] = (preg_match('/@len (\d+)/', $rMethod->getDocComment(), $matches))? $matches[1] : 1;
			
			$actions[] = $action;
		}
		
		return $actions;
	}
}